#pragma once

#include <iostream>
#include <string>
#include <memory>
#include <list>

#include "InetAddr.hpp"
#include "Log.hpp"
#include "Mutex.hpp"

using namespace My_Log;
using namespace My_Mutex;

class UserInterface
{
public:
    virtual ~UserInterface() = default;
    virtual void SendTo(int sokfd, const std::string &message) = 0;
    virtual bool operator==(const InetAddr &other) = 0;
};

// 单个用户对象
class User : public UserInterface
{
public:
    User(const InetAddr &id) : _id(id)
    {
    }
    void SendTo(int sokfd, const std::string &message) override
    {
        LOG(LogLevel::DEBUG) << "send message to: " << _id.GetStrAddr() << "info: " << message;
        ::sendto(sokfd, message.c_str(), message.size(), 0, _id.NetAddr(), _id.NetAddrLen());
    }
    bool operator==(const InetAddr &other) override
    {
        return _id == other;
    }
    ~User()
    {
    }

private:
    InetAddr _id;
};

// 管理用户
class UserManager
{
public:
    UserManager()
    {
    }
    void AddUser(const InetAddr &id)
    {
        LockGuard lockguard(_mutex);
        for (auto &u : _online_ptr)
        {
            if (*u == id)
            {
                LOG(LogLevel::DEBUG) << id.GetStrAddr() << "该用户已存在";
                return;
            }
        }
        LOG(LogLevel::DEBUG) << "新增用户: " << id.GetStrAddr();
        _online_ptr.push_back(std::make_shared<User>(id));
    }
    void DelUser(const InetAddr &id)
    {
    }
    void Route(int sokfd, std::string &message)
    {
        LockGuard lockguard(_mutex);
        for(auto& user:_online_ptr)
        {
            user->SendTo(sokfd, message);
        }
    }
    ~UserManager()
    {
    }

private:
    std::list<std::shared_ptr<UserInterface>> _online_ptr;
    Mutex _mutex;
};
